﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using AngleSharp.Dom;

namespace Sinc.ERP.Application;

/// <summary>
/// 库存调拨服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class TransferOrderService : CustomBaseService, IDynamicApiController
{
    private readonly SqlSugarRepository<TransferOrder> _transferOrderRep;
    private readonly SqlSugarRepository<TransferOrderProduct> _transferOrderProductRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public TransferOrderService(SqlSugarRepository<TransferOrder> transferOrderRep, SqlSugarRepository<TransferOrderProduct> transferOrderProductRep, ISqlSugarClient sqlSugarClient)
    {
        this._transferOrderRep = transferOrderRep;
        this._transferOrderProductRep = transferOrderProductRep;
        this._sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询库存调拨 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询库存调拨")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<TransferOrderOutput>> Page(PageTransferOrderInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _transferOrderRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => input.Code.Contains(u.Code))
            .WhereIF(input.ProductId != null, u => u.ProductId == input.ProductId)
            .WhereIF(input.FromCustomerId != null, u => u.FromCustomerId == input.FromCustomerId)
            .WhereIF(input.ToCustomerId != null, u => u.ToCustomerId == input.ToCustomerId)
            .Select<TransferOrderOutput>();
        var modelList = await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
        var customerList = this.CustomerService.DropdownData().Result;
        var productList = this.ProductService.DropdownData().Result;
        foreach (var model in modelList.Items)
        {
            model.ProductLabel = productList.FirstOrDefault(x => x.Id == model.ProductId)?.Name;
            model.FromCustomerLabel = customerList.FirstOrDefault(x => x.Id == model.FromCustomerId)?.Name;
            model.ToCustomerLabel = customerList.FirstOrDefault(x => x.Id == model.ToCustomerId)?.Name;
        }
        return modelList;
    }

    [DisplayName("查询库存调拨总数")]
    [ApiDescriptionSettings(Name = "GetSummary"), HttpPost]
    public async Task<TransferOrderOutput> GetSummary(PageTransferOrderInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _transferOrderRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Code), u => input.Code.Contains(u.Code))
            .WhereIF(input.ProductId != null, u => u.ProductId == input.ProductId)
            .WhereIF(input.FromCustomerId != null, u => u.FromCustomerId == input.FromCustomerId)
            .WhereIF(input.ToCustomerId != null, u => u.ToCustomerId == input.ToCustomerId)
            .Select(x => new TransferOrderOutput { Qty = SqlFunc.AggregateSum(x.Qty) })
            .FirstAsync();
        return await query;
    }

    /// <summary>
    /// 获取库存调拨详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取库存调拨详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<TransferOrderOutput> Detail([FromQuery] QueryByIdTransferOrderInput input)
    {
        var model = await _transferOrderRep.GetFirstAsync(u => u.Id == input.Id);
        var result = model?.Adapt<TransferOrderOutput>();
        if (model != null)
        {
            model.ProductList = await this._transferOrderProductRep.AsQueryable().Where(x => x.OrderId == model.Id).ToListAsync();
            result.CodeRange = model.ProductList.Select(x => x.Code).Join("\n");
        }
        return result;
    }

    /// <summary>
    /// 增加库存调拨 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加库存调拨")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddTransferOrderInput input)
    {
        var entity = input.Adapt<TransferOrder>();
        return await _transferOrderRep.InsertAsync(entity) ? entity.Id : 0;
    }

    public async Task Add(TransferOrder entity)
    {
        await _transferOrderRep.InsertAsync(entity);
        entity.ProductList.ForEach(x => x.OrderId = entity.Id);
        foreach (var orderProduct in entity.ProductList)
        {
            orderProduct.OrderId = entity.Id;
            await _transferOrderProductRep.InsertAsync(orderProduct);
        }
    }

    /// <summary>
    /// 更新库存调拨 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新库存调拨")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateTransferOrderInput input)
    {
        var entity = input.Adapt<TransferOrder>();
        await _transferOrderRep.AsUpdateable(entity).ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除库存调拨 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除库存调拨")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteTransferOrderInput input)
    {
        var entity = await _transferOrderRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _transferOrderRep.FakeDeleteAsync(entity);   //假删除
        //await _transferOrderRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除库存调拨 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除库存调拨")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")] List<DeleteTransferOrderInput> input)
    {
        var exp = Expressionable.Create<TransferOrder>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _transferOrderRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();

        return await _transferOrderRep.FakeDeleteAsync(list);   //假删除
        //return await _transferOrderRep.DeleteAsync(list);   //真删除
    }

    /// <summary>
    /// 导出库存调拨记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出库存调拨记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageTransferOrderInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportTransferOrderOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "库存调拨导出记录");
    }

    /// <summary>
    /// 下载库存调拨数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载库存调拨数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportTransferOrderOutput>(), "库存调拨导入模板");
    }

    /// <summary>
    /// 导入库存调拨记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入库存调拨记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportTransferOrderInput, TransferOrder>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {

                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x =>
                    {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.ProductId == null)
                        {
                            x.Error = "产品Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.Qty == null)
                        {
                            x.Error = "调拨数量不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.FromCustomerId == null)
                        {
                            x.Error = "来源客户Id不能为空";
                            return false;
                        }
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.ToCustomerId == null)
                        {
                            x.Error = "目标客户Id不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<TransferOrder>>();

                    var storageable = _transferOrderRep.Context.Storageable(rows)
                        .SplitInsert(_ => true)
                        .ToStorage();

                    if (rows.IsNotEmpty())
                    {
                        storageable.BulkCopy();
                        storageable.BulkUpdate();
                    }

                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });

            return stream;
        }
    }

    /// <summary>
    /// 导出库存调拨记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("修改调拨单备注")]
    [ApiDescriptionSettings(Name = "UpdateRemark"), HttpPost]
    public async Task UpdateRemark(UpdateTransferOrderRemarkInput input)
    {
        var entity = input.Adapt<TransferOrder>();
        await _transferOrderRep.AsUpdateable(entity).UpdateColumns(x => new { x.Remark, x.UpdateUserId, x.UpdateUserName, x.UpdateTime }).ExecuteCommandAsync();
    }
}
